#include "sntp_time.h"

#include "esp_sntp.h"
#include <time.h>
#include "esp_log.h"

const char *TAG = "sntp_time";
bool sntp_inited=false;

void initialize_sntp(void){
    ESP_LOGI(TAG, "Initializing SNTP");
    esp_sntp_setoperatingmode(SNTP_OPMODE_POLL);

    esp_sntp_setservername(0, "cn.pool.ntp.org"); // 中国区NTP服务的虚拟集群
    esp_sntp_setservername(1, "210.72.145.44"); // 国家授时中心服务器 IP 地址
    esp_sntp_setservername(2, "ntp1.aliyun.com");
    esp_sntp_setservername(3, "1.cn.pool.ntp.org");

    esp_sntp_init();
    // 设置时区（例如 UTC+8）
    setenv("TZ", "CST-8", 1);
    tzset();
    sntp_inited=true;
    /*
    // wait for time to be set
    time_t now = 0;
    struct tm timeinfo = {0};
    int retry = 0;
    const int retry_count = 10;
    while (timeinfo.tm_year < (2000 - 1900) && ++retry < retry_count) {
        ESP_LOGI(TAG, "Waiting for system time to be set... (%d/%d)", retry, retry_count);
        vTaskDelay(2000 / portTICK_PERIOD_MS);
        time(&now);
        localtime_r(&now, &timeinfo);
    }
    */
}

void get_current_time(
    char *sdate,size_t ssdate,
    char *sweek,size_t ssweek,
    char *stime,size_t sstime){
    time_t now;
    struct tm timeinfo;
    // char strftime_buf[64];
    const char *weekday[] = {"SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"};

    time(&now);
    localtime_r(&now, &timeinfo);
    if(timeinfo.tm_year < (2000 - 1900)){
        strcpy(sdate,"");
        strcpy(sweek,"");
        strcpy(stime,"");
    } else {
        snprintf(sweek, ssweek, "%s", weekday[timeinfo.tm_wday]);
        strftime(sdate, ssdate, "%Y-%m-%d", &timeinfo);
        strftime(stime, sstime, "%H:%M", &timeinfo);
    }
    ESP_LOGI(TAG, "Current time: %s", stime);
}
